package util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.zql.entity.AgencyEntity;

import dao.AgencyDaoInterface;

public class MybatisTool {
	private static SqlSession session;
	
	//静态块用来执行类属性的初始化
	static {
		try {
			InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
			SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder();
			SqlSessionFactory ssf = ssfb.build(inputStream);
			session = ssf.openSession();

		} catch (IOException e) {
			System.out.println("读取mybatis配置文件失败,获取SqlSessions失败");
		}
	}
	
	/**
	 * 数据库的插入数据方法,没有返回值
	 * @param agency 传入一个AgencyEntity对象
	 */
	public static void save(AgencyEntity agency) {
		AgencyDaoInterface dao = session.getMapper(AgencyDaoInterface.class);
		dao.save(agency);
		session.commit();
		//session.close();
	}
	/**
	 * 关闭session
	 */
	public static void close() {
		session.close();
	}

}
